package com.li.core.actionBase;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.Enumeration;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.actions.DispatchAction;

import com.cx.core.magazine.util.JSONTool;
import com.cx.core.magazine.util.TypeTokens;
import com.li.core.RequestEnvelope;
import com.li.core.ResponseEnvelope;
import com.li.core.factory.ServiceFactory;

public class ActionBase extends DispatchAction {
	protected static Log log = LogFactory.getLog(ActionBase.class);

	protected Object getBean(String beanid) {
		Object result = null;
		result = ServiceFactory.getBean(beanid);
		if (result == null) {
			if (log.isInfoEnabled()) {
				log.info("没有找到bean");
			}
			throw new RuntimeException("没有找到bean");
		}
		return result;
	}

	protected Object getAppContext() {
		return null;
	}

	protected RequestEnvelope splitParameters(HttpServletRequest request)
			throws Exception {
		// Gson gson = new Gson();
		// gson.fromJson(new
		// InputStreamReader(request.getInputStream()),TypeTokens.TYPETOKEN_REQUESTENVELOPE.getType());
		StringBuffer sb = new StringBuffer(2048);
//		byte[] buffer = new byte[1024];
//		while(request.getInputStream().read(buffer) != -1){
//			sb.append(buffer);
//		}
		//sb.append(buffer);
		System.out.println(sb.toString());
	    BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));  
        String line = null;  
       
        while((line = br.readLine())!=null){  
            sb.append(line);  
        }  
		
		RequestEnvelope<String, String> res = (RequestEnvelope<String, String>) JSONTool
				.stringToObject(sb.toString(),
						TypeTokens.TYPETOKEN_REQUESTENVELOPE);
		if(res == null){
			 res = new RequestEnvelope<String, String>();
		}
		Enumeration ens = request.getParameterNames();
		String key = null;
		while(ens.hasMoreElements()){
			key = (String)ens.nextElement();
			if(!res.getBody().containsKey(key)){
				res.addParameter(key, request.getParameter(key));
			}
		}
		return res;
	}

	protected void writeResponse(HttpServletResponse response,
			ResponseEnvelope rsp) throws Exception {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("UTF-8");
		Writer writer = response.getWriter();
		log.debug(JSONTool.ObjectToJSON(rsp));
		writer.write(JSONTool.ObjectToJSON(rsp));
	}
}
